﻿#include "Database.h"
#include <QDebug>
#include "QSqlError"
#include "Ext/FilterQuery.h"
#include <QSqlDatabase>
#include <QSqlDriver>
#include "UserTable.h"
#include "UserInfoTable.h"

namespace TCServer
{
	namespace Store
	{
		Database::Database()
		{
			// init sql
			//QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
			//db.setHostName("rds2pq5p1ai4620z3616o.mysql.rds.aliyuncs.com");
			//db.setDatabaseName("tc");
			//db.setUserName("weizehua");
			//db.setPassword("wzh0403");

#ifdef _TCDEBUG
			const char *server = "192.168.2.135";
			const char *database = "tc";
			const char *username = "tcuser";
			const char *password = "Wzh0403!";
#else
			const char *server = "119.29.159.124";
			const char *database = "tc";
			const char *username = "tcuser";
			const char *password = "Weizehua9766534";
#endif // _TCDEBUG
			db = QSqlDatabase::addDatabase("QMYSQL");
			db.setHostName(server);
			db.setDatabaseName(database);
			db.setUserName(username);
			db.setPassword(password);

			bool ok = db.open();
			if (!ok)
			{
				qFatal("Failed to connect to database. Reason : %s", db.lastError().text());
			}
            qInfo() << "Connected to SQL server : " << server << ", using databse : " << database;

			static QSet<QSqlDriver::DriverFeature> featuresNeeded = {
				QSqlDriver::DriverFeature::QuerySize,
				QSqlDriver::DriverFeature::PreparedQueries,
				QSqlDriver::DriverFeature::PositionalPlaceholders,
				QSqlDriver::DriverFeature::LastInsertId,
			};
			for(QSqlDriver::DriverFeature feature : featuresNeeded)
			{
				if (!db.driver()->hasFeature(feature))
				{
					qWarning() << "sql driver not support : QSqlDriver::DriverFeature::" << feature << endl;
				}
			}
		}

		Database::~Database()
		{
		}

		bool Database::createDatabase()
		{
            // create schema
            FilterQuery q;
            q.prepare("CREATE DATABASE IF NOT EXISTS `tc` /*!40100 DEFAULT CHARACTER SET utf8 */;");
            q.exec();

            // create tables
            UserTable::create();
            UserInfoTable::create();
            return true;
		}

// 		bool Database::dropDatabase()
// 		{
// 			FilterQuery q;
// 			q.prepare(R"(
// 			DROP DATABASE `tc`;
// 			)");
// 			q.exec();
// 			return true;
// 		}

		Database* Database::instance()
		{
			static Database* _instance = new Database;
			return _instance;
		}

        bool Database::reconnect()
        {
            return db.open();
        }

	}
}